package com.qf.vote.controller;

import cn.hutool.jwt.JWT;
import com.qf.vote.entity.PhoneToken;
import com.qf.vote.entity.Ticket;
import com.qf.vote.service.TicketService;
import com.qf.vote.service.impl.PhoneTokenServiceImpl;
import com.qf.vote.utils.Constants;
import com.qf.vote.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 前端控制器
 *
 * @author yyq
 * @since 2023-02-25
 */
@RestController
@RequestMapping("/vote")
public class VotingController {
    @Autowired
    TicketService ticketService;
    @Autowired
    PhoneTokenServiceImpl phoneTokenService;

    @RequestMapping("/ticket")
    public ResultVo ticket() {
        List<Ticket> ticketList = ticketService.getTicket();
        return ResultVo.ok(ticketList);
    }

    @RequestMapping("/setToken")
    public ResultVo userPhone(String phone) {
        ResultVo ok = ResultVo.ok();
        String getToken = phoneTokenService.selectToken(phone);
        if (getToken == "-1") {
            String newToken = phoneTokenService.insertToken(phone);
            ok.put("msg", newToken);
        } else {
            boolean validate = JWT.of(getToken).setKey(Constants.SECRET.getBytes(StandardCharsets.UTF_8)).validate(0);
            if (validate) {
                ok.put("msg", getToken);
            } else {
                String newToken = phoneTokenService.insertToken(phone);
                ok.put("msg", newToken);
            }
        }
        return ok;
    }


}













